import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, logout, getUserInfo } from '@/api/auth'
import { Message } from '@arco-design/web-vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('admin_token') || '')
  const userInfo = ref(null)
  const isLoggedIn = computed(() => !!token.value)

  // 登录
  const loginUser = async (credentials) => {
    try {
      const data = await login(credentials)
      token.value = data.accessToken
      userInfo.value = data.user
      localStorage.setItem('admin_token', token.value)
      localStorage.setItem('admin_user', JSON.stringify(userInfo.value))
      Message.success('登录成功')
      return true
    } catch (error) {
      console.error('登录失败:', error)
      return false
    }
  }

  // 登出
  const logoutUser = async () => {
    try {
      await logout()
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      token.value = ''
      userInfo.value = null
      localStorage.removeItem('admin_token')
      localStorage.removeItem('admin_user')
      Message.success('已退出登录')
    }
  }

  // 初始化用户信息
  const initUser = () => {
    const savedUser = localStorage.getItem('admin_user')
    if (savedUser && token.value) {
      try {
        userInfo.value = JSON.parse(savedUser)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        logoutUser()
      }
    }
  }

  // 更新用户信息
  const updateUserInfo = (info) => {
    userInfo.value = { ...userInfo.value, ...info }
    localStorage.setItem('admin_user', JSON.stringify(userInfo.value))
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    loginUser,
    logoutUser,
    initUser,
    updateUserInfo
  }
})
